package concurrent.threadscheduling;

/**
 * 线程调度复习
 * @Author Antony
 * @Since 2018/12/17 11:10
 */
public class ThreadSchedulingStudy {

    public static void main(String[] args) {
        threadLoopScheduling();
    }


    /**
     * N个线程循环打印指定信息
     */
    public static void threadLoopScheduling(){
        Object lock = new Object();
        Runnable t1 = new LoopThread("A","B", lock);
        Runnable t2 = new LoopThread("B","A", lock);

        t2.run();
        t1.run();
    }


    private static volatile String printVal = "A";
    static class LoopThread implements Runnable{
        private String val;
        private String nextVal;
        private Object lockObj;

        public LoopThread(String val, String nextVal, Object lockObj) {
            this.val = val;
            this.nextVal = nextVal;
            this.lockObj = lockObj;
        }

        @Override
        public void run() {
            for (int i=0; i<10; i++){
                synchronized (lockObj){
                    while(!val.equals(printVal)){
                        try {
                            lockObj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Current Thread print " + val);
                    printVal = nextVal;
                    lockObj.notify();
                }
            }
        }
    }
}
